import requests
import json
import threading
import time
from PyQt5.QtWidgets import *
from check_fun import  extract_bookmarks

class UrlChecker(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('网址检测工具')

        self.layout = QVBoxLayout()

        self.label = QLabel('请输入谷歌收藏夹文件路径：')
        self.layout.addWidget(self.label)

        self.filePathEdit = QLineEdit()
        self.layout.addWidget(self.filePathEdit)

        self.checkButton = QPushButton('检测')
        self.checkButton.clicked.connect(self.start_check)
        self.layout.addWidget(self.checkButton)

        self.progressBar = QProgressBar()
        self.layout.addWidget(self.progressBar)

        self.resultText = QTextEdit()
        self.layout.addWidget(self.resultText)
        # 设置窗口大小
        self.resize(600, 400)  # 宽度 600，高度 400

        self.setLayout(self.layout)

    def start_check(self):
        # 每次点击检测前清空结果文本框
        self.resultText.clear()
        #清空进度条
        self.progressBar.reset()
        filePath = self.filePathEdit.text()
        if not filePath.endswith('Bookmarks'):
            # self.resultText.append('输入的文件路径对应的文件名不是 Bookmarks，请重新输入！')
            QMessageBox.warning(self, "错误", "输入的文件路径对应的文件名不是 Bookmarks，请重新输入！")
            return
        self.thread = threading.Thread(target=self.check_urls,args=(filePath,))
        self.thread.start()

    def check_urls(self,filePath):
        try:
            with open(filePath, 'r', encoding='utf-8') as file:
                data = json.load(file)
                bookmarks = {}  # 用于存储名称和网址的字典
                extract_bookmarks(data['roots']['bookmark_bar'],bookmarks)

                total_bookmarks = len(bookmarks)
                self.progressBar.setMaximum(total_bookmarks)
                failed_bookmarks = {}  # 存储失联网址及其名称

                for index, (name, url) in enumerate(bookmarks.items()):
                    url = url.strip()
                    try:
                        response = requests.get(url, timeout=5)
                        if response.status_code!= 200:
                            failed_bookmarks[name] = url
                    except requests.exceptions.RequestException:
                        failed_bookmarks[name] = url
                    self.progressBar.setValue(index + 1)
                    time.sleep(0.1)  # 模拟耗时操作，可根据实际情况调整或去除

                if failed_bookmarks:
                    self.resultText.append('以下网址失联：')
                    for name, url in failed_bookmarks.items():
                        self.resultText.append(f'{name}: {url}')
                else:
                    self.resultText.append('所有网址均正常')
        except FileNotFoundError:
            self.resultText.append('文件未找到，请检查路径！')
        except json.JSONDecodeError:
            self.resultText.append('文件格式不正确，请确认是谷歌收藏夹文件！')



if __name__ == '__main__':
    app = QApplication([])
    window = UrlChecker()
    window.show()
    app.exec_()